package com.cn.codebrush.链表;

import java.util.HashMap;
import java.util.Map;

public class No82删除排序链表中的重复元素II {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(2);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(4);
        ListNode node6 = new ListNode(5);

        l1.next = node1;
        node1.next=node2;
        node2.next=node3;
        /*node3.next=node4;
        node4.next=node5;
        node5.next=node6;*/

        System.out.println(deleteDuplicates(l1));
    }

    /**
     * 借助 Map 进行记忆
     * @param head
     * @return
     */
    public static ListNode deleteDuplicates(ListNode head) {
        if(head == null){
            return null;
        }
        ListNode temp = head;
        ListNode pre = head;
        ListNode cur = head.next;
        Map map = new HashMap<>();
        while(cur != null){
            if(cur.val == pre.val){
                pre.next = cur.next;
                map.putIfAbsent(pre.val,pre);
            }else{
                pre = cur;
            }
            cur = cur.next;
        }

        while(map.containsKey(temp.val)){
            temp=temp.next;
            if(temp == null){
                break;
            }
        }
        if(temp == null){
            return null;
        }
        ListNode res = temp;
        ListNode pre2 = temp;
        ListNode cur2 = temp.next;
        while(cur2 != null){
            if(map.containsKey(cur2.val)){
                pre2.next = cur2.next;
            }else {
                pre2 = cur2;
            }
            cur2 = cur2.next;
        }

        return res;
    }
}
